<template>
    <div class="app-container">
        <!--查询表单-->
        <div class="search-div">
            <el-form label-width="70px" size="small" :inline="true">

                <el-form-item label="角色名称">
                    <el-input style="width: 140px" v-model="queryRoleVO.roleName" placeholder="请输入角色名称"
                        @keyup.enter.native="getRoleData"></el-input>
                </el-form-item>

                <el-form-item label="状态">
                    <el-select v-model="queryRoleVO.status" placeholder="角色状态" clearable size="small" style="width: 140px">
                        <el-option :key="1" label="正常" :value="1" />
                        <el-option :key="0" label="停用" :value="0" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="getRoleData()">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetData()">重置</el-button>
                </el-form-item>


                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
                            @click="edit">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                            @click="batchRemove">批量删除</el-button>
                    </el-col>
                </el-row>

            </el-form>
        </div>

        <!-- 表格 -->
        <el-table v-loading="listLoading" :data="list" @selection-change="handleSelectionChange">

            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column label="序号" width="70" align="center">
                <template slot-scope="scope">
                    {{ (page - 1) * limit + scope.$index + 1 }}
                </template>
            </el-table-column> -->

            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="roleCode" label="角色编码" />
            <el-table-column prop="status" label="状态" align="center" width="100">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
                        @change="handleStatusChange(scope.row)" />
                </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" :show-overflow-tooltip="true" width="160" />
            <el-table-column prop="createTime" label="创建时间" width="160" />
            <el-table-column label="操作" width="200" align="center">
                <template slot-scope="scope"  v-if="scope.row.id !== 1">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row.id)" title="修改" />
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row.id)"
                        title="删除" />
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <!-- 实现显示每页的数量 -->
        <el-pagination :current-page="queryRoleVO.pageNum" :total="total" :page-sizes="[10, 20, 30, 40]"
            :page-size="queryRoleVO.pageSize" style="padding: 30px 0; text-align: right;"
            layout="total, prev, pager, next, jumper" @current-change="getRoleData" />

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色编码" prop="roleCode">
                    <el-input v-model="form.roleCode" placeholder="请输入角色编码" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status">
                        <el-radio :key="0" :label="0">停用</el-radio>
                        <el-radio :key="1" :label="1">正常</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="菜单权限">
                    <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
                    <el-checkbox v-model="menuNodeAll"
                        @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
                    <el-checkbox v-model="form.menuCheckStrictly"
                        @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
                    <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="id"
                        :check-strictly="!form.menuCheckStrictly" empty-text="加载中，请稍候" :props="defaultProps"></el-tree>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.description" type="textarea" placeholder="请输入内容"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>
// 引入定义接口的js文件
import { getRoleList, saveRole, getSysRoleById, editRole, updateRoleStatus, deleteRoleById, batchDeleteRole } from '@/api/system/sysRole'
import { treeSelect, roleMenuTreeSelect } from '@/api/system/sysMenu'

export default {

    // 定义数据类型
    data() {
        return {
            listLoading: true, // 数据是否正在加载
            list: [], // 角色列表
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            total: 0, // 总记录数
            page: 1, // 页码
            limit: 10, // 每页记录数
            queryRoleVO: {  // 查询条件
                pageNum: 1,
                pageSize: 10,
                roleName: undefined,
                status: undefined,
                createTime: undefined,
                updateTime: undefined
            },
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 表单参数
            form: {},
            // 菜单列表
            menuOptions: [],
            menuExpand: false,
            menuNodeAll: false,
            defaultProps: {
                children: "children",
                label: "menuName"
            },
            // 改变状态
            changeStatus: {
                id: undefined,
                status: undefined,
            },

            // 表单校验
            rules: {
                roleName: [
                    { required: true, message: "角色名称不能为空", trigger: "blur" }
                ],
                roleKey: [
                    { required: true, message: "角色编码不能为空", trigger: "blur" }
                ]
            },
        }
    },

    // 页面渲染之前获取数据
    created() {
        this.getRoleData()
    },
    // 定义方法
    methods: {
        getRoleData() {

            getRoleList(this.queryRoleVO).then(response => {
                // console.log(response)
                this.listLoading = false
                this.list = response.data.rows
                this.total = response.data.total
            })
        },
        resetData() {
            this.queryRoleVO = {}
            this.getRoleData()
        },

        /** 查询菜单树结构 */
        getMenuTreeselect() {
            treeSelect().then(response => {
                this.menuOptions = response.data;
            });
        },

        /** 根据角色ID查询菜单树结构 */
        getRoleMenuTreeselect(id) {
            return roleMenuTreeSelect(id).then((response) => {
                this.menuOptions = response.data.menus
                return response.data
            })
        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },


        // 所有菜单节点数据
        getMenuAllCheckedKeys() {
            // 目前被选中的菜单节点
            let checkedKeys = this.$refs.menu.getCheckedKeys();
            // 半选中的菜单节点
            let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
            checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
            return checkedKeys;
        },

        // 树权限（展开/折叠）
        handleCheckedTreeExpand(value, type) {
            if (type == 'menu') {
                let treeList = this.menuOptions;
                for (let i = 0; i < treeList.length; i++) {
                    this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
                }
            } else if (type == 'dept') {
                let treeList = this.deptOptions;
                for (let i = 0; i < treeList.length; i++) {
                    this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
                }
            }
        },
        // 树权限（全选/全不选）
        handleCheckedTreeNodeAll(value, type) {
            if (type == 'menu') {
                this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
            } else if (type == 'dept') {
                this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
            }
        },
        // 树权限（父子联动）
        handleCheckedTreeConnect(value, type) {
            if (type == 'menu') {
                this.form.menuCheckStrictly = value ? true : false;
            } else if (type == 'dept') {
                this.form.deptCheckStrictly = value ? true : false;
            }
        },


        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },

        // 表单重置
        reset() {
            if (this.$refs.menu != undefined) {
                this.$refs.menu.setCheckedKeys([]);
            }
            this.menuExpand = false,
            this.menuNodeAll = false,
            this.form = {
                id: undefined,
                roleName: undefined,
                roleCode: undefined,
                status: 1,
                menuIds: [],
                menuCheckStrictly: true,
                description: undefined
            };
            this.resetForm("form");
        },

        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.getMenuTreeselect();
            this.open = true;
            this.title = "添加角色";
        },


        /** 修改按钮操作 */
        edit(id) {
            this.reset()
            const roleMenu = this.getRoleMenuTreeselect(id)
            getSysRoleById(id).then((response) => {
                this.form = response.data
                this.open = true
                this.$nextTick(() => {
                    roleMenu.then((res) => {
                        const checkedKeys = res.checkedKeys
                        checkedKeys.forEach((v) => {
                            this.$nextTick(() => {
                                this.$refs.menu.setChecked(v, true, false)
                            })
                        })
                    })
                })
                this.title = '修改角色'
            })
        },

        // 角色状态修改
        handleStatusChange(row) {
            const text = row.status === '1' ? '启用' : '停用'
            this.changeStatus.id = row.id
            this.changeStatus.status = row.status

            updateRoleStatus(this.changeStatus).then(response => {
                if (response.code) {
                    this.$message.success(response.message || '操作成功')
                    this.getRoleData()
                }
            })

        },


        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id !== undefined) {
                        this.form.menuIds = this.getMenuAllCheckedKeys();
                        editRole(this.form).then(response => {
                            this.$message.success(response.message || '修改成功');
                            this.open = false;
                            this.getRoleData();
                        });
                    } else {
                        this.form.menuIds = this.getMenuAllCheckedKeys();
                        saveRole(this.form).then(response => {
                            this.$message.success(response.message || '新增成功');
                            // this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getRoleData();
                        });
                    }
                }
            });
        },


        // 根据id删除数据
        handleDelete(id) {
            // debugger
            this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => { // promise
                // 点击确定，远程调用ajax
                return deleteRoleById(id)
            }).then((response) => {
                this.getRoleData()
                this.$message.success(response.message || '删除成功')
            }).catch(() => {
                this.$message.info('取消删除')
            })
        },

        // 批量删除
        batchRemove() {
            if (this.ids.length === 0) {
                this.$message.warning('请选择要删除的记录！')
                return
            }
            this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 点击确定，远程调用ajax
                // 遍历selection，将id取出放入id列表
                // var idList = []
                // this.ids.forEach(item => {
                //     idList.push(item.id)
                //     console.log(idList.length)
                //     console.log(idList)
                // })
                // 调用api接口
                return batchDeleteRole(this.ids)
            }).then((response) => {
                this.getRoleData()
                this.$message.success(response.message)
            }).catch(error => {
                if (error === 'cancel') {
                    this.$message.info('取消删除')
                }
            })
        }



    }
}
</script>